#include <unistd.h> 
#include <sys/types.h> 
#include <sys/stat.h> 
#include <unistd.h> 
#include <dirent.h> 
#include <string.h> 
#include <stdlib.h> 
#include <stdio.h>
#define READ_BUF_SIZE 1024
int ugetpid_byname(char* proc_name, int* pid, int n)
{
    int retn = 0;

    DIR *dir;
    struct dirent *next;
    int i=0;

    ///proc中包括当前的进程信息,读取该目录
    dir = opendir("/proc");
    if (!dir)
    {
        fprintf(stderr, "cannot open /proc");
        return retn;
    }

    //遍历
    while ((next = readdir(dir)) != NULL)
    {
        FILE *status;
        char filename[READ_BUF_SIZE];
        char buffer[READ_BUF_SIZE];
        char name[READ_BUF_SIZE];

        /* Must skip ".." since that is outside /proc */
        if (strcmp(next->d_name, "..") == 0)
            continue;

        /* If it isn't a number, we don't want it */
        if (!isdigit(*next->d_name))
            continue;
        //设置进程
        sprintf(filename, "/proc/%s/status", next->d_name);
        if (! (status = fopen(filename, "r")) )
        {
            continue;
        }
        if (fgets(buffer, READ_BUF_SIZE-1, status) == NULL)
        {
            fclose(status);
            continue;
        }
        fclose(status);

        //得到进程id
        /* Buffer should contain a string like "Name:   binary_name" */
        sscanf(buffer, "%*s %s", name);
        if (strcmp(name, proc_name) == 0) 
        {
            pid[retn] = strtol(next->d_name, NULL, 0);
            retn ++;

            if(retn >= n) {
                break;
            }
        }
    }

    return retn;
}


int main()
{
    int pid;
    int n = ugetpid_byname("streammgrd", &pid, 1);
    printf("n=%d, pid=%d.\n", n, pid);

    return 0;
}
